package com.leetCode.tree;

/**
 * Description:
 * Copyright:   Copyright (c)2019
 * Company:     zefu
 *
 * @author: 张李鑫
 * @version: 1.0
 * Create at:   2021-10-22 10:02:25
 * <p>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2021-10-22     张李鑫                     1.0         1.0 Version
 */
 class IsValidBST {

    public static class Info {
        public boolean isBST;
        public int max;
        public int min;

        public Info(boolean isBST, int max, int min) {
            this.isBST = isBST;
            this.max = max;
            this.min = min;
        }
    }


    public boolean isValidBST(TreeNode root) {
        return process(root).isBST;
    }


    public static Info process(TreeNode treeNode) {
        if (treeNode == null) {
            return null;
        }
        Info leftInfo = process(treeNode.left);
        Info rightInfo = process(treeNode.right);
        int max = treeNode.val;
        int min = treeNode.val;
        if (leftInfo != null) {
            max = Math.max(max, leftInfo.max);
            min = Math.min(min, leftInfo.min);
        }

        if (rightInfo != null) {
            max = Math.max(max, rightInfo.max);
            min = Math.min(min, rightInfo.min);
        }

        boolean isBST = true;
        if (leftInfo != null && leftInfo.max >= treeNode.val) {
            isBST = false;
        }

        if (rightInfo != null && rightInfo.min <= treeNode.val) {
            isBST = false;
        }

        if (leftInfo != null && !leftInfo.isBST) {
            isBST = false;
        }

        if (rightInfo != null && !rightInfo.isBST) {
            isBST = false;
        }

        return new Info(isBST, max, min);
    }


}
